import os
import sys
import logging

def get_application_base_dir():
    """获取应用程序的基础目录 - 兼容PyInstaller打包"""
    if getattr(sys, 'frozen', False):
        # 打包后的可执行文件
        if hasattr(sys, '_MEIPASS'):
            # PyInstaller 打包，返回可执行文件所在目录
            return os.path.dirname(sys.executable)
        else:
            # 其他打包工具
            return os.path.dirname(sys.executable)
    else:
        # 开发环境，返回脚本文件所在目录
        return os.path.dirname(os.path.abspath(__file__))

class Config:
    """应用配置类"""

    # 基础配置
    SECRET_KEY = os.environ.get('SECRET_KEY') or 'cfx2000'
    DEBUG = os.environ.get('FLASK_ENV') == 'production'

    # 获取正确的基础目录
    BASE_DIR = get_application_base_dir()

    # 文件夹配置 - 相对于可执行文件目录
    UPLOAD_FOLDER = os.path.join(BASE_DIR, 'uploads')
    OUTPUT_FOLDER = os.path.join(BASE_DIR, 'outputs')
    STATIC_FOLDER = os.path.join(BASE_DIR, 'static')
    LIBRARY_FOLDER = os.path.join(BASE_DIR, 'library')
    PREVIEW_FOLDER = os.path.join(BASE_DIR, 'previews')
    TEMP_FOLDER = os.path.join(BASE_DIR, 'temp')

    # 数据库配置
    DATABASE_FILE = os.path.join(BASE_DIR, 'database.db')

    # 文件上传配置
    MAX_CONTENT_LENGTH = 10000 * 1024 * 1024  # 10GB
    ALLOWED_VIDEO_EXTENSIONS = {'.mp4', '.mov'}
    ALLOWED_IMAGE_EXTENSIONS = {'.jpg', '.jpeg', '.png'}

    # 处理配置
    DEFAULT_CANVAS_WIDTH = 1080
    DEFAULT_CANVAS_HEIGHT = 1920
    DEFAULT_OUTPUT_FORMAT = 'mp4'

    # 清理配置
    PREVIEW_RETENTION_HOURS = 1     # 预览文件默认保留1小时
    TEMP_RETENTION_HOURS = 24       # 临时文件默认保留24小时
    OUTPUT_RETENTION_DAYS = 7       # 输出文件默认保留7天
    TASK_RETENTION_HOURS = 24       # 已完成任务记录默认保留24小时

    # 日志配置
    LOG_DIR = os.path.join(BASE_DIR, 'logs')
    LOG_MAX_BYTES = 20 * 1024 * 1024  # 20MB
    LOG_BACKUP_COUNT = 10
    LOG_RETENTION_DAYS = 30

    # 分页配置
    DEFAULT_PAGE_SIZE = 12
    MAX_PAGE_SIZE = 100

    @classmethod
    def init_folders(cls):
        """初始化必要的文件夹"""
        folders = [
            cls.UPLOAD_FOLDER,
            cls.OUTPUT_FOLDER,
            cls.STATIC_FOLDER,
            cls.LIBRARY_FOLDER,
            cls.PREVIEW_FOLDER,
            cls.TEMP_FOLDER,
            cls.LOG_DIR,
            # 创建子目录
            os.path.join(cls.LIBRARY_FOLDER, 'human'),
            os.path.join(cls.LIBRARY_FOLDER, 'background')
        ]

        for folder in folders:
            try:
                os.makedirs(folder, exist_ok=True)
                # 确保目录是可写的
                if not os.access(folder, os.W_OK):
                    print(f"⚠️ 警告: 目录 {folder} 不可写")
            except Exception as e:
                print(f"❌ 创建目录失败 {folder}: {e}")

    @classmethod
    def setup_logging(cls):
        """设置日志配置"""
        # 确保日志目录存在
        os.makedirs(cls.LOG_DIR, exist_ok=True)

        logging.basicConfig(
            level=logging.INFO if not cls.DEBUG else logging.DEBUG,
            format='%(asctime)s %(levelname)s %(name)s: %(message)s'
        )

    @classmethod
    def get_resource_path(cls, relative_path):
        """获取资源文件路径 - 兼容PyInstaller"""
        if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'):
            # 打包后的临时目录中的资源
            base_path = sys._MEIPASS
        else:
            # 开发环境
            base_path = os.path.dirname(os.path.abspath(__file__))

        return os.path.join(base_path, relative_path)


class DevelopmentConfig(Config):
    """开发环境配置"""
    DEBUG = True


class ProductionConfig(Config):
    """生产环境配置"""
    DEBUG = False


class TestingConfig(Config):
    """测试环境配置"""
    TESTING = True
    DATABASE_FILE = ':memory:'


# 配置字典
config = {
    'development': DevelopmentConfig,
    'production': ProductionConfig,
    'testing': TestingConfig,
    'default': DevelopmentConfig
}